import 'dart:convert';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hxdj/common/components/my_clip_rect.dart';
import 'package:hxdj/common/components/my_countdown_button.dart';
import 'package:hxdj/common/components/my_scaffold.dart';
import 'package:hxdj/common/components/my_scrollView.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/env_config/env.dart';
import 'package:hxdj/common/my_common.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/login/login_viewmodel.dart';
import 'package:provider/provider.dart';
import 'package:dio5_log/dio_log.dart';

class LoginPage extends StatefulWidget {
  static String routeName = "/login";

  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //手机号
  final TextEditingController _phoneNumbercontroller = TextEditingController();

  //验证码
  final TextEditingController _codeController = TextEditingController();

  //短信验证码
  final TextEditingController _smsCodeController = TextEditingController();

  late LoginViewModel viewModel;

  //自定义数据框
  Widget _buildCustomTextFild(String placeholder, TextEditingController controller, int maxLength, Widget? rightWidget,
      {EdgeInsetsGeometry padding = const EdgeInsets.only(left: 10, right: 10)}) {
    return Container(
      height: 45,
      padding: const EdgeInsets.symmetric(horizontal: 17.5),
      margin: const EdgeInsets.only(top: 15),
      child: MyBorder(
        radius: 25,
        color: MyColours.eff2fc,
        backgroundColor: MyColours.eff2fc,
        child: Container(
            padding: padding,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                    child: TextField(
                  controller: controller,
                  inputFormatters: [
                    LengthLimitingTextInputFormatter(maxLength),
                    placeholder == "请输入图形验证码"
                        ? FilteringTextInputFormatter.singleLineFormatter
                        : FilteringTextInputFormatter.digitsOnly
                  ], //    text, multiline, number, phone, datetime, emailAddress, url, visiblePassword, name, streetAddress, none,
                  decoration: InputDecoration(
                    hintText: placeholder,
                    hintStyle: MyTextStyles.textGray14,
                    border: InputBorder.none, // 隐藏下划线
                    contentPadding: const EdgeInsets.fromLTRB(15, 0.0, 10.0, 12.0), // 内容内边距
                    focusedBorder:
                        const OutlineInputBorder(borderSide: BorderSide(width: 0, color: Colors.transparent)),
                    disabledBorder:
                        const OutlineInputBorder(borderSide: BorderSide(width: 0, color: Colors.transparent)),
                    enabledBorder:
                        const OutlineInputBorder(borderSide: BorderSide(width: 0, color: Colors.transparent)),
                  ),

                  keyboardType:
                      placeholder == "请输入图形验证码" ? TextInputType.visiblePassword : TextInputType.phone, // 设置为手机号键盘
                )),
                Container(child: rightWidget ?? const MyImage(imageName: "ic_tabbar_se_reservation", width: 20)),
              ],
            )),
      ),
    );
  }

  //登录按钮
  _buildLoginButton() {
    return GestureDetector(
      onTap: () async {
        //校验数据
        if (_phoneNumbercontroller.text.isEmpty) {
          EasyLoading.showToast("手机号不能为空");
        } else if (!CommonPlugin.isPhone(_phoneNumbercontroller.text)) {
          EasyLoading.showToast("手机格式不正确");
        } else if (_smsCodeController.text.isEmpty) {
          EasyLoading.showToast("短信验证码不能为空");
        } else if (viewModel.isAgreeProtocol == false) {
          EasyLoading.showToast("请同意隐私政策");
        } else {
          viewModel.login(_phoneNumbercontroller.text, _smsCodeController.text);

          // viewModel.login("18310070875", "6666");
        }
      },
      child: Container(
        margin: const EdgeInsets.only(top: 30),
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 15),
          decoration: BoxDecoration(
            color: MyColours.appMain,
            //设置四周圆角 角度
            borderRadius: BorderRadius.circular(30),
          ),
          alignment: Alignment.center,
          child: const Text("登录", style: TextStyle(fontSize: 15, color: Colors.white, fontWeight: FontWeight.w700)),
        ),
      ),
    );
  }

  //到计时按钮
  _buildMyCountdownButton() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      decoration: BoxDecoration(
        color: MyColours.appMain,
        borderRadius: BorderRadius.circular(20),
      ),
      child: MyCountdownButton(
        countdown: 60,
        key: GlobalKey(debugLabel: DateTime.now().microsecondsSinceEpoch.toString()),
        textController: _phoneNumbercontroller,
        codeController: _codeController,
        onOver: () {
          viewModel.setIsGetSmsCode(false);
        },
        onStart: () {
          viewModel.updateSmsVerificationCode(_phoneNumbercontroller.text, captcha: _codeController.text);
        },
        isStartDown: viewModel.isGetSmsCode,
      ),
    );
  }

  //图文验证码
  _buildGraphicVerificationButton() {
    return GestureDetector(
        onTap: () {
          //更新图文验证码
          viewModel.updateGraphicVerificationCode();
          _codeController.clear();
        },
        child: ClipRRect(
            //圆角图片
            //  borderRadius: BorderRadius.circular(8),
            borderRadius: const BorderRadius.only(topRight: Radius.circular(30.0), bottomRight: Radius.circular(30.0)),
            child: Image.memory(
              base64.decode(viewModel.captchaBase64.split(',')[1]),
              height: 45, //设置高度
              width: 120, //设置宽度
              fit: BoxFit.fill, //填充
              gaplessPlayback: true, //防止重绘
            )

            // Image.network(imageUrl, width: , height: ),
            ));
  }

  //隐私政策
  _buildPrivacyPolicy() {
    return Container(
      margin: const EdgeInsets.only(left: 53, right: 10),
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              viewModel.setAgreeProtocol();
            },
            child: MyImage(imageName: viewModel.isAgreeProtocol ? "ic_select" : "ic_un_select", width: 15),
          ),
          TextButton(
            onPressed: () {
              debugPrint("点击了政策 我已阅读并知晓《用户协议》和《隐私政策》");
            },
            child: RichText(
                text:
                    TextSpan(style: const TextStyle(color: MyColours.textBlack, fontSize: 12, height: 1.2), children: [
              const TextSpan(text: '我已阅读并知晓'),
              TextSpan(
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      debugPrint("点击了协议");
                    },
                  text: '《用户协议》',
                  style: const TextStyle(color: MyColours.appMain)),
              const TextSpan(text: '和'),
              TextSpan(
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      debugPrint("点击了政策");
                    },
                  text: '《隐私政策》',
                  style: const TextStyle(color: MyColours.appMain)),
            ])),
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (Env.getInstance()!.versionEnvDesc == "T1") {
        ///display overlay button 显示悬浮按钮
        showDebugBtn(context, btnColor: MyColours.appMain, btnSize: 50);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
        resizeToAvoidBottomInset: false,
        showAppbar: false,
        body: ChangeNotifierProvider<LoginViewModel>(
            create: (_) => LoginViewModel(),
            child: Selector<LoginViewModel, String>(selector: (_, model) {
              viewModel = model;
              return model.captchaBase64;
            }, builder: (ctx, strint1, child) {
              viewModel.context = ctx;
              debugPrint('Consumer build');
              return SafeArea(
                child: MyScrollView(crossAxisAlignment: CrossAxisAlignment.center, children: [
                  //icon
                  Container(
                      padding: EdgeInsets.only(top: 40.h),
                      child: MyClipRect(radius: 10.w, imageName: "ic_app", width: 100.w)),
                  Container(
                    padding: EdgeInsets.only(top: 45.h, bottom: 15.h),
                    alignment: Alignment.center,
                    child: Column(
                      children: [
                        MyText("验证码登录", textStyle: MyTextStyles.textBlackBold16),
                        MyBorder(
                            color: MyColours.appMain,
                            backgroundColor: MyColours.appMain,
                            radius: 1.5,
                            child: SizedBox(
                              width: 25.w,
                              height: 3,
                            ))
                      ],
                    ),
                  ),

                  //手机号
                  _buildCustomTextFild(
                      '请输入手机号码', _phoneNumbercontroller, 11, MyImage(imageName: "ic_login_account", width: 15.w),
                      padding: EdgeInsets.only(left: 10.w, right: 25.w)),

                  //图形验证
                  if (viewModel.isShowGraphicVerificationCode)
                    Selector<LoginViewModel, String>(
                      selector: (_, model) => model.captchaBase64,
                      builder: (_, str, c) {
                        return _buildCustomTextFild('请输入图形验证码', _codeController, 4, _buildGraphicVerificationButton(),
                            padding: EdgeInsets.only(right: 0, left: 10.w));
                      },
                    ),

                  Selector<LoginViewModel, bool>(
                    selector: (_, model) => model.isGetSmsCode,
                    builder: (_, str, c) {
                      return _buildCustomTextFild('请输入短信验证码', _smsCodeController, 4, _buildMyCountdownButton());
                    },
                  ),

                  Selector<LoginViewModel, bool>(
                    selector: (_, model) => model.isAgreeProtocol,
                    builder: (_, str, c) {
                      return _buildPrivacyPolicy();
                    },
                  ),
                  //隐私政策

                  //登录按钮
                  _buildLoginButton(),
                ]),
              );
            })));
  }
}
